package cn.t.service.user;

import cn.t.core.mode.YesNoEnum;
import cn.t.core.service.ServiceImpl;
import cn.t.core.enums.base.BaseStatusEnum;
import cn.t.model.user.RoleSkuDO;
import cn.t.repository.user.RoleSkuRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 *
 * @author l
 */
@Slf4j
@Service
@AllArgsConstructor
public class RoleSkuService extends ServiceImpl<RoleSkuDO, RoleSkuRepository> {

//    public void assignRights(Long roleId, List<SkuDTO> skuList) {
//        boolean result = removeByRoleId(roleId);
//
//        if (skuList != null) {
//            skuList.forEach(skuDTO -> {
//                RoleSkuDO roleSkuDO = new RoleSkuDO();
//                roleSkuDO.setRoleId(roleId);
//                roleSkuDO.setSkuCode(skuDTO.getSkuCode());
//                roleSkuDO.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
//                roleSkuDO.setGmtCreated(new Date());
//                repository.add(roleSkuDO);
//            });
//        }
//        // 清理缓存
//        String redisKey = String.format(REDIS_KEY__SKU_ROLE_VO, roleId);
//        applicationEventPublisher.publishEvent(new UserRedisClearEvent(redisKey, redisKey));
//    }

    public List<RoleSkuDO> findByRoleId(Set<Long> roleIdList) {

        if (roleIdList == null) {
            return null;
        }
        List<RoleSkuDO> ret = new ArrayList<>();

        for (Long roleId : roleIdList) {
            List<RoleSkuDO> roleResourceList = findByRoleId(roleId);
            if (roleResourceList == null || roleResourceList.isEmpty()) {
                continue;
            }
            ret.addAll(roleResourceList);
        }

        return ret;
    }

    public List<RoleSkuDO> findByRoleId(Long roleId) {
        RoleSkuDO template = new RoleSkuDO();
        template.setRoleId(roleId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        template.setIsDeleted(YesNoEnum.FALSE);

        return repository.findByModel(template, 0, 10000, "id", "asc");
    }


    public boolean removeByRoleId(Long roleId) {
        return repository.removeByRoleId(roleId);
    }


    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;


}
